package org.yiming.tools.mqtt.client.client.command;

import lombok.RequiredArgsConstructor;
import org.yiming.tools.mqtt.client.ApplicationContext;
import org.yiming.tools.mqtt.client.client.MqttClient;
import org.yiming.tools.mqtt.client.command.Command;

import java.util.Optional;

/**
 * @author renwenpeng
 * date  2022/3/25 5:14 下午
 */
@RequiredArgsConstructor
public class UseMqttClientCommand implements Command {

    private final String[] names = new String[]{"use"};

    private final ApplicationContext applicationContext;

    @Override
    public String[] name() {
        return names;
    }

    @Override
    public String execute(String[] args) {
        // 校验args
        int argsMinLength = 1;
        if (args == null || args.length < argsMinLength) {
            return "args incorrect";
        }
        MqttCommandContext mqttCommandContext = MqttCommandContext.getSingleton();
        Optional<MqttClient> mqttClientOptional = Optional.ofNullable(applicationContext.getMqttClientMap().get(args[0]));
        if (mqttClientOptional.isPresent()) {
            mqttCommandContext.setMqttClient(mqttClientOptional.get());
            return String.format("found [%s]", mqttClientOptional.get().getName());
        } else {
            return "not found";
        }
    }

    @Override
    public String[] helpContent() {
        return new String[]{"use", "{name:local}"};
    }
}
